package com.inxedu.os.edu.controller.website;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.inxedu.os.common.constants.CommonConstants;
import com.inxedu.os.common.controller.BaseController;
import com.inxedu.os.common.util.FileUtils;
import com.inxedu.os.common.util.FreeMarkerUtil;
import com.inxedu.os.common.util.ObjectUtils;
import com.inxedu.os.common.util.StringUtils;
import com.inxedu.os.edu.constants.enums.WebSiteProfileType;
import com.inxedu.os.edu.controller.Template.AdminTemplateFileController;
import com.inxedu.os.edu.entity.webpage.Webpage;
import com.inxedu.os.edu.entity.webpagetemplate.WebpageTemplate;
import com.inxedu.os.edu.entity.website.WebsiteProfile;
import com.inxedu.os.edu.service.webpage.WebpageService;
import com.inxedu.os.edu.service.webpagetemplate.WebpageTemplateService;
import com.inxedu.os.edu.service.website.WebsiteNavigateService;
import com.inxedu.os.edu.service.website.WebsiteProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网站配置管理
 * @author www.inxedu.com
 */
@Controller
@RequestMapping("/admin")
public class AdminWebsiteProfileController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AdminWebsiteProfileController.class);
	@Autowired
	private WebsiteProfileService websiteProfileService;
	@Autowired
	private WebpageService webpageService;
	@Autowired
	private WebpageTemplateService webpageTemplateService;
	@Autowired
	private WebsiteNavigateService websiteNavigateService;
	private static final String getWebSiteList = getViewPath("/admin/website/profile/website_profile_list");// 网站配置管理页面
	private static final String toupdateWebSite = getViewPath("/admin/website/profile/website_profile_update");// 更新网站配置管理页面
	private static final String getWebSiteOnline = getViewPath("/admin/website/profile/website_profile_online");// 在线咨询

	private static final String ICONAME="favicon.ico";//定义ico文件常量
	/**
	 * 查询网站配置 根据Type
	 */
	@RequestMapping("/websiteProfile/find/{type}")
	public String getWebSiteList(HttpServletRequest request, Model model, @PathVariable("type") String type) {
		String returnUrl = "";
		try {
			String flag = request.getParameter("flag");
			Map<String, Object> map = websiteProfileService.getWebsiteProfileByType(type);
			if (StringUtils.isNotEmpty(flag)) {
				returnUrl = toupdateWebSite;// 跳转到更新页面
			} else {
				returnUrl = getWebSiteList;// 列表页
			}
			model.addAttribute("webSiteMap", map);
			model.addAttribute("type", type);
		} catch (Exception e) {
			logger.error("getWebSiteList", e);
		}
		return returnUrl;
	}
	/**
	 * 更新管理根据类型
	 */
	@RequestMapping("/websiteProfile/update")
	public String updateWebSiteByType(HttpServletRequest request, Model model, @RequestParam("type") String type,@PathVariable("icoFile") MultipartFile icoFile) {
		try {
			if (ObjectUtils.isNotNull(type) && StringUtils.isNotEmpty(type)) {
				Gson gson = new Gson();
				JsonParser jsonParser = new JsonParser();
				Map<String, Object> map = new HashMap<String, Object>();
				if (type.equals(WebSiteProfileType.web.toString())) {
					map.put("email", request.getParameter("email"));// 公司邮箱
					map.put("phone", request.getParameter("phone"));// 24小时电话
					map.put("workTime", request.getParameter("workTime"));// 工作时间
					map.put("copyright", request.getParameter("copyright"));// 备案
					map.put("author", request.getParameter("author"));// 作者
					map.put("keywords", request.getParameter("keywords"));// 关键词
					map.put("description", request.getParameter("description"));// 描述
					map.put("imgUrl", request.getParameter("imgUrl"));// clientID
					map.put("title", request.getParameter("title"));//
					map.put("location",request.getParameter("location"));//公司地址
					map.put("company", request.getParameter("company"));// 网校名称
					map.put("logoUrl", request.getParameter("logoUrl"));// 网校logo
					/*保存首页模板的头和尾*/
					Webpage webpage = new Webpage();
					webpage.setPublishUrl("/index.html");
					List<Webpage> webpages =  webpageService.queryWebpageList(webpage);
					Webpage helloPage = webpages.get(0);
					WebpageTemplate webpageTemplate = new WebpageTemplate();
					webpageTemplate.setPageId(helloPage.getId());
					webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
					List<WebpageTemplate> templates = webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
					/*创建头部和尾部的ftl文件*/
					StringBuffer header=new StringBuffer();
					header.append(FileUtils.readLineFile(request.getSession().getServletContext().getRealPath("/")+templates.get(0).getTemplateUrl()));
					FileUtils.writeFile(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/ftl/"+"header.ftl",header.toString());
					StringBuffer footer=new StringBuffer();
					footer.append(FileUtils.readLineFile(request.getSession().getServletContext().getRealPath("/")+templates.get(templates.size()-1).getTemplateUrl()));
					FileUtils.writeFile(request.getSession().getServletContext().getRealPath("/")+"footer.ftl",footer.toString());
					/*获取头部和尾部的动态数据*/
					Map<String, Object> root = new HashMap<>();
					Map<String,Object> webmap=(Map<String,Object>)websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.web.toString()).get(WebSiteProfileType.web.toString());
					/*ctx*/
					root.put("ctx",CommonConstants.contextPath);
					/*首页导航*/
					Map<String,Object> navigatemap = websiteNavigateService.getWebNavigate();
					root.put("websiteNavigates",navigatemap.get("INDEX"));
					/*网站尾部信息*/
					root.put("webmap", webmap);
					/*生成头部和尾部的html页面*/
					FreeMarkerUtil.analysisTemplate(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/ftl/","header.ftl",request.getSession().getServletContext().getRealPath("/")+"header.html",root);
					FreeMarkerUtil.analysisTemplate(request.getSession().getServletContext().getRealPath("/"),"footer.ftl",request.getSession().getServletContext().getRealPath("/")+"footer.html",root);
					String templateFooter = AdminTemplateFileController.txt2String(new File(request.getSession().getServletContext().getRealPath("/")+"footer.html"));
					String templateHeader = AdminTemplateFileController.txt2String(new File(request.getSession().getServletContext().getRealPath("/")+"header.html"));
					/*把头部和尾部的文件内容写入数据库*/
					Map map2 = new HashMap();
					map2.put("footer",templateFooter);
					map2.put("header",templateHeader);
					Gson gson2 = new Gson();
					JsonParser jsonParser2 = new JsonParser();
					JsonObject jsonObject = jsonParser2.parse(gson2.toJson(map2)).getAsJsonObject();
					if (ObjectUtils.isNotNull(jsonObject) && StringUtils.isNotEmpty(jsonObject.toString())) {// 如果不为空进行更新
						WebsiteProfile websiteProfile = new WebsiteProfile();// 创建websiteProfile
						websiteProfile.setType("template");
						websiteProfile.setDesciption(jsonObject.toString());
						websiteProfileService.updateWebsiteProfile(websiteProfile);
					}

					//上传ico文件
					if (!icoFile.isEmpty()) {
						// 获得项目的真实路径
						String path = request.getSession().getServletContext().getRealPath("/");
						File file = new File(path + "/" + ICONAME);
						if (!file.exists()) {
							file.mkdirs();
						}
						try {
							icoFile.transferTo(file);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				// 统计代码
				if (type.equals(WebSiteProfileType.censusCode.toString())) {
					map.put("censusCodeString", request.getParameter("censusCodeString"));// thirdloginstatus第三方登录是否开启
				}

				// 将map转化json串
				JsonObject jsonObject = jsonParser.parse(gson.toJson(map)).getAsJsonObject();
				if (ObjectUtils.isNotNull(jsonObject) && StringUtils.isNotEmpty(jsonObject.toString())) {// 如果不为空进行更新
					WebsiteProfile websiteProfile = new WebsiteProfile();// 创建websiteProfile
					websiteProfile.setType(type);
					websiteProfile.setDesciption(jsonObject.toString());
					websiteProfileService.updateWebsiteProfile(websiteProfile);
				}
				webpageService.publishAll(true,request);
			}
		} catch (Exception e) {
			logger.error("AdminWebsiteProfileController.updateWebSiteByType", e);
		}
		return "redirect:/admin/websiteProfile/find/" + type;
	}

	/**
	 * 查询在线咨询
	 */
	@RequestMapping("/websiteProfile/online")
	public String getWebsiteOnline(HttpServletRequest request, Model model) {
		try {
			// 查询在线咨询详情
			Map<String, Object> map = websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.online.toString());
			model.addAttribute("websiteonlinemap", map);
		} catch (Exception e) {
			logger.error("getWebsiteOnline", e);
			return setExceptionRequest(request, e);
		}
		return getWebSiteOnline;
	}

	/**
	 * 更新WebsiteOnline
	 */
	@RequestMapping("/websiteProfile/online/update")
	public String updateWebsiteOnline(HttpServletRequest request) {
		try {
			JsonParser jsonParser = new JsonParser();
			Map<String, String> map = new HashMap<String, String>();
			map.put("onlineUrl", request.getParameter("onlineUrl"));// 链接
			map.put("onlineImageUrl", request.getParameter("onlineImageUrl"));// 图片链接
			map.put("onlineKeyWord", request.getParameter("onlineKeyWord"));// 开关
			// 将map转化json串
			JsonObject jsonObject = jsonParser.parse(gson.toJson(map)).getAsJsonObject();
			if (ObjectUtils.isNotNull(jsonObject) && StringUtils.isNotEmpty(jsonObject.toString())) {// 如果不为空进行更新
				WebsiteProfile websiteProfile = new WebsiteProfile();// 创建websiteProfile
				websiteProfile.setType(WebSiteProfileType.online.toString());
				websiteProfile.setDesciption(jsonObject.toString());
				websiteProfileService.updateWebsiteProfile(websiteProfile);
			}
		} catch (Exception e) {
			logger.error("updateWebsiteOnline", e);
		}
		return "redirect:/admin/websiteProfile/online";
	}

	/**
	 * ajax 更新管理根据类型
	 */
	@RequestMapping("/ajax/updateWebsiteProfile/{type}")
	@ResponseBody
	public Object updWebSiteByTypeAjax(HttpServletRequest request, Model model, @PathVariable("type") String type) {
		Map<String,Object> json = new HashMap<String,Object>();
		try {
			if (ObjectUtils.isNotNull(type) && StringUtils.isNotEmpty(type)) {
				Gson gson = new Gson();
				JsonParser jsonParser = new JsonParser();
				Map<String, String> map = new HashMap<String, String>();
				if (type.equals(WebSiteProfileType.web.toString())) {
					map.put("email", request.getParameter("email"));// 公司邮箱
					map.put("phone", request.getParameter("phone"));// 24小时电话
					map.put("workTime", request.getParameter("workTime"));// 工作时间
					map.put("copyright", request.getParameter("copyright"));// 备案
					map.put("author", request.getParameter("author"));// 作者
					map.put("keywords", request.getParameter("keywords"));// 关键词
					map.put("description", request.getParameter("description"));// 描述
					map.put("title", request.getParameter("title"));//
					map.put("company", request.getParameter("company"));// 网校名称
				}

				// 统计代码
				if (type.equals(WebSiteProfileType.censusCode.toString())) {
					map.put("censusCodeString", request.getParameter("censusCodeString"));// thirdloginstatus第三方登录是否开启
				}
				// 将map转化json串
				JsonObject jsonObject = jsonParser.parse(gson.toJson(map)).getAsJsonObject();
				if (ObjectUtils.isNotNull(jsonObject) && StringUtils.isNotEmpty(jsonObject.toString())) {// 如果不为空进行更新
					WebsiteProfile websiteProfile = new WebsiteProfile();// 创建websiteProfile
					websiteProfile.setType(type);
					websiteProfile.setDesciption(jsonObject.toString());
					websiteProfileService.updateWebsiteProfile(websiteProfile);
				}
			}
			json = this.setJson(true, "", "");
		} catch (Exception e) {
			logger.error("AdminWebsiteProfileController.updateWebSiteByType", e);
			json = this.setJson(false, "", "");
		}
		return json;
	}


	/**
	 * ajax 查询网站配置 根据Type
	 */
	@RequestMapping("/ajax/getWebsiteProfile/{type}")
	@ResponseBody
	public Object getWebSiteListAjax(HttpServletRequest request, Model model, @PathVariable("type") String type) {
		Map<String,Object> json = new HashMap<String,Object>();
		try {
			Map<String, Object> map = (Map<String, Object>)websiteProfileService.getWebsiteProfileByType(type).get(type);
			json = this.setJson(true, "", map);
		} catch (Exception e) {
			logger.error("getWebSiteList", e);
			json = this.setJson(false, "", "");
		}
		return json;
	}

}
